#include "login.h"

#include "ui_login.h"

login::login(QWidget *parent) : QDialog(parent), ui(new Ui::login) {
    ui->setupUi(this);
    setWindowIcon(QIcon(":/login-box-line.png"));
    sock = new QTcpSocket();
    sock->connectToHost("10.62.139.92", 9988);
    connect(sock, SIGNAL(connected()), this, SLOT(handConnect()));
}

login::~login() { delete ui; }

void login::on_buttonLogin_clicked() {
    Name = ui->editName->text();
    QString passwd = ui->editPasswd->text();
    if (ui->editName->text() == "" || ui->editPasswd->text() == "") {
        qDebug() << "内容为空";
        QMessageBox::information(NULL, "错误", "用户名或密码不能为空！",
                                 QMessageBox::Yes);
    } else {
        QString registerData = "#02|" + Name + "|" + passwd;
        registerData.toStdString().c_str();
        qDebug() << registerData;
        sock->write(registerData.toUtf8());
    }
}

void login::on_buttonRegister_clicked() {
    QString name = ui->editName->text();
    QString passwd = ui->editPasswd->text();
    if (ui->editName->text() == "" || ui->editPasswd->text() == "") {
        qDebug() << "内容为空";
        QMessageBox::information(NULL, "错误", "用户名或密码不能为空！",
                                 QMessageBox::Yes);
    } else {
        QString registerData = "#01|" + name + "|" + passwd;
        registerData.toStdString().c_str();
        qDebug() << registerData;
        sock->write(registerData.toUtf8());
    }
}

void login::handConnect() {
    ui->buttonRegister->setEnabled(true);
    ui->buttonLogin->setEnabled(true);
    connect(sock, SIGNAL(readyRead()), this, SLOT(handRead()));
}

void login::handRead() {
    QByteArray recvData = sock->readAll();
    QString recvStr(recvData);
    QStringList recvStrList = recvStr.split('|');
    if (recvStrList[0] == "#01") {
        if (recvStrList[1] == "0") {
            qDebug() << recvStrList[2];
            msgbox("\n注册成功\n");
        } else {
            qDebug() << "failed: " << recvStrList[2];
            msgbox("\n用户已存在，请登录\n");
        }
    }
    if (recvStrList[0] == "#02") {
        if (recvStrList[1] == "0") {
            qDebug() << recvStrList[2];
            disconnect(sock, SIGNAL(readyRead()), 0, 0);
            MainWindow *mw = new MainWindow(sock);
            mw->show();
            connect(this, SIGNAL(sendData(QString)), mw,
                    SLOT(getData(QString)));
            emit sendData(Name);
            this->hide();
        } else {
            qDebug() << "failed: " << recvStrList[2];
            msgbox("\n账号或者密码错误\n");
        }
    }
}

void login::msgbox(QString msg) {
    QMessageBox::information(NULL, "提示", msg, QMessageBox::Yes);
}
